<template>
  <el-card class="flex flex-col gap-1 editor overflow-visible">
    <QuillEditor ref="quillEditor" theme="bubble" placeholder="记录下此刻的想法、念头……" v-model:content="input" contentType="html"
      @update:content="handleUpdateContent"
      :toolbar="['bold', 'italic', 'underline', 'strike', { 'background': ['#c15048', '#3f8378', '#cb9d37', '#6f7e26', '#4c8538', '#3f8378', '#3d7da7', '#436fe3', '#b4528c', '#b4528c', '#8458e4', '#a6a6a6'] }]" />
    <div class="text-right">
      <el-button @click="submit" type="primary" :disabled="!input" size="small">
        <el-icon>
          <Check />
        </el-icon>
      </el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import storeService, { NoteDbDoc } from '../../store/index'
import { Check } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'

const quillEditor = ref<typeof QuillEditor>()
const input = ref('');
const noteDbDoc = ref<NoteDbDoc | null>(null);

const emit = defineEmits(['save']);

const handleUpdateContent = async (content) => {
  input.value = content

  if (!noteDbDoc.value) {
    noteDbDoc.value = await storeService.create({ content: input.value })
    console.log({
      component: '<Editor />',
      function: 'watch(input)',
      stage: 'create noteDbDoc',
      noteDbDoc: noteDbDoc.value
    })
  } else {
    noteDbDoc.value = await storeService.update(noteDbDoc.value._id, { content: input.value, _rev: noteDbDoc.value._rev })
  }
}

const submit = () => {
  input.value = ''
  noteDbDoc.value = null
  console.log(quillEditor.value)
  // Issue: https://github.com/vueup/vue-quill/issues/484
  quillEditor.value?.setHTML?.('')
  emit('save')
}

</script>
<style scoped>
.editor :deep(.ql-editor.ql-blank::before) {
  color: var(--el-border-color);
}
</style>
